package com.kye.express.business.personal_setting.modify_name;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;

import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityModifyNameOrCompanyBinding;
import com.kye.express.utils.StringFormatUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.user.User;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class ModifyNameOrCompanyActivity extends BaseAppCompatActivity implements ModifyNameOrCompanyContract.ModifyNameOrCompanyView {

    private static final String KEY_TYPE = "KEY_TYPE";

    public static final String KEY_NAME = "KEY_NAME";
    public static final String KEY_COMPANY = "KEY_COMPANY";

    private ActivityModifyNameOrCompanyBinding mBinding;
    private ModifyNameOrCompanyContract.ModifyNameOrCompanyPresenter mPresenter;
    private Dialog mDialog;

    public static void startActivity(Context context, String keyName) {
        context.startActivity(new Intent(context, ModifyNameOrCompanyActivity.class)
                .putExtra(KEY_TYPE, keyName));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_modify_name_or_company);
        Intent intent = getIntent();
        String type = intent.getStringExtra(KEY_TYPE);
        mBinding.setType(KEY_NAME.equals(type));

        initEvent();
        initData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_modify_name_or_company, menu);
        return true;
    }

    private void initEvent() {
        setSupportActionBar(mBinding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        RxToolbar.navigationClicks(mBinding.toolbar)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        finish();
                    }
                });

        Observable<CharSequence> editTextObservable = RxTextView.textChanges(mBinding.editTextItem)
                .cache();

        editTextObservable
                .map(new Function<CharSequence, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence) throws Exception {
                        return !TextUtils.isEmpty(charSequence);
                    }
                })
                .compose(this.<Boolean>bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.setDeleteButtonVisibility(aBoolean);
                    }
                });

        editTextObservable
                .map(new Function<CharSequence, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence) throws Exception {
                        return mBinding.getType() ? charSequence.length() >= 2 : charSequence.length() >= 3;
                    }
                })
                .compose(this.<Boolean>bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        MenuItem item = mBinding.toolbar.getMenu().findItem(R.id.save);
                        if (item == null) return;

                        item.setEnabled(aBoolean);
                    }
                });

        RxToolbar.itemClicks(mBinding.toolbar)
                .map(new Function<MenuItem, Object>() {
                    @Override
                    public Object apply(MenuItem menuItem) throws Exception {
                        String value = mBinding.editTextItem.getText().toString().trim();

                        if (mBinding.getType()) {
                            if (StringFormatUtils.checkNameIsChinese(value)) {
                                return new IllegalArgumentException(getString(R.string.error_name_just_is_chinese));
                            }

                            if (value.contains(getString(R.string.common_mr)) || value.contains(getString(R.string.common_miss))) {
                                return new IllegalArgumentException(getString(R.string.error_name_cant_contains_appellation));
                            }
                        } else {
                            if (!value.contains(getString(R.string.common_company)) && !value.contains(getString(R.string.common_factory))) {
                                return new IllegalArgumentException(getString(R.string.error_company_need_contains));
                            }
                        }

                        return menuItem;
                    }
                })
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof IllegalArgumentException) {
                            ToastManager.show(ModifyNameOrCompanyActivity.this, ((IllegalArgumentException) o).getMessage());
                            return;
                        }

                        String value = mBinding.editTextItem.getText().toString().trim();

                        mPresenter.editPersonalSetting(mBinding.getUser(), mBinding.getType(), value);
                    }
                });
    }

    private void initData() {
        setTitle(mBinding.getType() ? R.string.modify_name_or_company_title_name : R.string.modify_name_or_company_title_company);

        mPresenter = new ModifyNameOrCompanyContract.ModifyNameOrCompanyPresenter();
        mPresenter.bind(this);
        mPresenter.getUser();
    }

    @Override
    public void onError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onUser(User user) {
        mBinding.setUser(user);
    }

    @Override
    public void onSuccess() {
        finish();
    }
}
